package com.ld.action;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.ld.tool.window.TranslateMainWindow;
import com.ld.tool.window.TranslatePanel;
import com.ld.translate.TranslateFactory;
import org.jetbrains.annotations.NotNull;

//
public class Translate extends AnAction {

    public Translate(){
    }
    @Override
    public void update(@NotNull AnActionEvent e) {
        super.update(e);
    }

    @Override
    public void actionPerformed(AnActionEvent e) {
        Editor editor = CommonDataKeys.EDITOR.getData(e.getDataContext());
        if (editor != null){
            String selectedText = editor.getSelectionModel().getSelectedText();
            if (selectedText != null && selectedText != ""){
                Project project = e.getProject();
                TranslateMainWindow.showToolWindow(project);
                ApplicationManager.getApplication().executeOnPooledThread(()->{
                    TranslatePanel translatePanel = null;
                    for (int i=0;i<3;i++){
                        translatePanel = TranslateMainWindow.getTranslatePanel(project);
                        if (translatePanel == null){
                            try {
                                Thread.sleep(100);
                            } catch (InterruptedException e1) {
                                e1.printStackTrace();
                            }
                        }else {
                            break;
                        }
                    }
                    if (translatePanel != null){
                        translatePanel.context.setText(TranslateFactory.getInstance().tokens(selectedText));
//                        translatePanel.startTranslate();
                    }
                });
            }
        }
    }
}